import 'dart:convert';

import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:sonora/bloc/home/sj_home_event.dart';
import 'package:sonora/bloc/home/sj_home_state.dart';
import 'package:sonora/models/sj_content_more_item_data.dart';
import 'package:sonora/models/sj_login_response_data.dart';
import 'package:sonora/models/sj_response_data.dart';
import 'package:sonora/models/sj_works_model.dart';
import 'package:sonora/services/sj_api_video_service.dart';
import 'package:sonora/utils/sj_medal_utils.dart';
import 'package:sonora/utils/sj_record_util.dart';
import 'package:sonora/views/appbar/sj_appbar.dart';
import 'package:sonora/views/bottom_sheet/sj_bottom_sheet_view.dart';
import 'package:sonora/views/dialog/sj_medal_obtain_dailog.dart';

import '../../bloc/home/sj_home_bloc.dart';
import '../../config/sj_app_initial.dart';
import '../../utils/sj_storage_utils.dart';
import 'sj_bottom_recorder.dart';

@RoutePage()
class SjArticleDetailPage extends StatefulWidget {
  const SjArticleDetailPage({super.key, required this.data});

  final SjWorksModel data;

  @override
  State<SjArticleDetailPage> createState() => _SjArticleDetailPageState();
}

class _SjArticleDetailPageState extends State<SjArticleDetailPage> {
  final FocusNode _focusNode = FocusNode();
  late final SjHomeBloc _homeBloc = getit<SjHomeBloc>();

  final TextEditingController _textEditingController = TextEditingController();

  bool hiddenInput = true;
  bool hiddenRecord = true;

  bool isLiked = false;

  List<SjWorksCommentModel> comments = [];

  List<String> works = [];

  @override
  void initState() {
    super.initState();
    isLiked = widget.data.isLiked ?? false;

    _focusNode.addListener(_onFocusChange);

    comments = List.from(widget.data.comments ?? []);

    works = List.from(widget.data.works ?? []);
    if (!works.contains(widget.data.cover!)) {
      works.add(widget.data.cover!);
    }

    () async {
      SjLoginData? loginData = await SjStorageUtils.getLoginInfo();
      if (widget.data.userId == loginData!.userInfo!.userId) {
        noMore = true;
        setState(() {});
      }
      _homeBloc
        ..add(const SjHomeEventLoadedFollowList())
        ..add(const SjHomeEventLoadedBlockList());
    }();
  }

  bool noMore = false;

  void _onFocusChange() {
    if (_focusNode.hasFocus) {
      hiddenRecord = true;
      setState(() {});
      print("TextField has gained focus");
    } else {
      print("TextField has lost focus");
    }
  }

  void doLike() {
    _homeBloc.changeLike(widget.data, true);
  }

  void doUnlike() {
    _homeBloc.changeLike(widget.data, false);
  }

  // 显示交互菜单
  void showMenu() {
    print('----------${_homeBloc.state.blokList?.length}');
    print('----------${widget.data.userId}');
    String followStr = 'Follow';
    for (var item in (_homeBloc.state.friendList ?? [])) {
      if (item.userId == widget.data.userId) {
        followStr = 'UnFollow';
        break;
      }
    }
    String blockStr = 'Block';
    for (var item in (_homeBloc.state.blokList ?? [])) {
      if (item.broadcasterId == widget.data.userId) {
        blockStr = 'UnBlock';
        break;
      }
    }
    final List<Map<String, dynamic>> list0 = [
      {'name': followStr, 'type': 1},
      {'name': blockStr, 'type': 2},
      {
        'name': 'Report',
        'type': 3,
        'subItems': [
          {
            'name': 'Pornographic',
            'type': 3,
          },
          {
            'name': 'False gender',
            'type': 3,
          },
          {
            'name': 'Fraud',
            'type': 3,
          },
          {
            'name': 'Political sensitive',
            'type': 3,
          },
          {
            'name': 'Other',
            'type': 3,
          },
        ]
      },
    ];
    final list = list0.map((e) => SjContentMoreItemData.fromJson(e)).toList();
    SjBottomSheetView.show(context: context, options: list, onOptionSelected: _onOptionSelected);
  }

  void _onOptionSelected(BuildContext context, SjContentMoreItemData moreItem) {
    if (moreItem.subItems != null && moreItem.subItems!.isNotEmpty) {
      SjBottomSheetView.show(context: context, options: moreItem.subItems!, onOptionSelected: _onOptionSelected);
    } else {
      if (moreItem.type == 1) {
        if (moreItem.name == 'Follow') {
          _homeBloc.add(SjHomeEventFriend(followUserId: widget.data.userId ?? ''));
        } else {
          _homeBloc.add(SjHomeEventUnFriend(followUserId: widget.data.userId ?? ''));
        }
      } else if (moreItem.type == 2) {
        if (moreItem.name == 'Block') {
          _homeBloc.add(SjHomeEventInsertRecord(
              broadcasterId: widget.data.userId,
              complainCategory: 'Block',
              complainSub: 'Other',
              callback: () {
                Navigator.pop(context);
              }));
        } else {
          // context.read<SjMineBloc>().add(SjMineEventRemoveBlock(broadcasterId: widget.data.userId ?? ''));
        }
      } else if (moreItem.type == 3) {
        _homeBloc.add(SjHomeEventInsertReport(
          broadcasterId: widget.data.userId,
          complainCategory: 'Report',
          complainSub: moreItem.name,
        ));
      }
    }
  }

  String descTras = '';

  void trans() async {
    SjResponseData data = await getit.get<SjApiVideoService>().languageTranslate(widget.data.des!);
    if (data.data != null) {
      descTras = data.data['translations'][0]['translatedText'];
      setState(() {});
    }
  }

  @override
  void dispose() {
    _focusNode.removeListener(_onFocusChange);
    _focusNode.dispose();
    _textEditingController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider.value(
        value: _homeBloc,
        child: GestureDetector(
          onTap: () {
            print('>>>>>>>>>>>>>>>>>>>>>>>detail page');
            _focusNode.unfocus();
            setState(() {
              hiddenInput = true;
            });
          },
          child: Scaffold(
            resizeToAvoidBottomInset: false,
            backgroundColor: Colors.white,
            extendBody: true,
            //底部NavigationBar透明
            extendBodyBehindAppBar: true,
            //顶部Bar透明
            appBar: SjAppbar(
              backgroundColor: Colors.transparent,
              elevation: 0,
              shadowColor: Colors.transparent,
              leading: IconButton(
                padding: const EdgeInsets.only(left: 20),
                onPressed: () {
                  Navigator.pop(context);
                },
                icon: Image.asset(
                  'assets/images/nav_back.png',
                  width: 30,
                ),
              ),
              actions: [
                if (noMore == false)
                  Container(
                    margin: const EdgeInsets.only(right: 20),
                    child: IconButton(
                      onPressed: () {
                        showMenu();
                      },
                      icon: Image.asset(
                        'assets/images/nav_more.png',
                        width: 30,
                      ),
                    ),
                  ),
              ],
            ),
            body: Stack(
              fit: StackFit.expand,
              children: [
                _headerWidget(),
                Positioned(child: _contentWidget(), top: 350, left: 0, right: 0, bottom: 0),
                Positioned(child: _bottomWidget(), bottom: 0, left: 0, right: 0),
                Positioned(
                  bottom: 0,
                  left: 0,
                  right: 0,
                  child: AnimatedPadding(
                    padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
                    duration: const Duration(milliseconds: 10),
                    child: Visibility(
                      visible: !hiddenInput,
                      child: Container(
                        padding: const EdgeInsets.only(left: 20, right: 20, top: 10, bottom: 10),
                        color: Colors.white,
                        child: Column(
                          children: [
                            Row(
                              children: [
                                GestureDetector(
                                    onTap: () {
                                      setState(() {
                                        hiddenRecord = !hiddenRecord;
                                        _focusNode.unfocus();
                                      });
                                    },
                                    child: Image.asset(
                                      hiddenRecord ? 'assets/images/input_voice.png' : 'assets/images/keyboard.png',
                                      width: 32,
                                      height: 32,
                                    )),
                                Expanded(
                                    child: Stack(children: [
                                  Container(
                                    margin: const EdgeInsets.only(left: 10),
                                    decoration: BoxDecoration(
                                      color: const Color(0x0D000000),
                                      borderRadius: BorderRadius.circular(20),
                                    ),
                                    padding: const EdgeInsets.only(left: 10),
                                    child: TextField(
                                      focusNode: _focusNode,
                                      controller: _textEditingController,
                                      style: const TextStyle(fontFamily: 'Galada'),
                                      decoration: const InputDecoration(
                                        hintText: 'Enter your ideas...',
                                        border: InputBorder.none,
                                      ),
                                    ),
                                  ),
                                  Positioned(
                                    right: 0,
                                    top: 0,
                                    bottom: 0,
                                    child: GestureDetector(
                                      onTap: () {
                                        send();
                                      },
                                      child: Container(
                                        padding: const EdgeInsets.only(left: 20, right: 20),
                                        decoration: BoxDecoration(
                                          borderRadius: BorderRadius.circular(23),
                                          color: Colors.black,
                                        ),
                                        alignment: Alignment.center,
                                        child: const Text(
                                          'Send',
                                          style: TextStyle(color: Color(0xFFF95DA7), fontFamily: 'Galada', fontSize: 16),
                                        ),
                                      ),
                                    ),
                                  ),
                                ])),
                              ],
                            ),
                            _recordWidget(),
                          ],
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ));
  }

  void send() async {
    SjLoginData? loginData = await SjStorageUtils.getLoginInfo();
    SjWorksCommentModel? msg;
    if (hiddenRecord) {
      String content = _textEditingController.text;
      msg =
          SjWorksCommentModel(nickname: loginData!.userInfo!.nickname!, avatar: loginData.userInfo!.avatarUrl, content: content, type: 1);
    } else {
      msg = SjWorksCommentModel(
          nickname: loginData!.userInfo!.nickname!,
          avatar: loginData.userInfo!.avatarUrl,
          content: currentRecordPath,
          type: 2,
          duration: duration);
    }

    await _homeBloc.addComment(widget.data, msg);
    comments.insert(0, msg);

    setState(() {
      _focusNode.unfocus();
      hiddenInput = true;
    });

    // first commnet show medal dialog
    bool firstComment = await SjStorageUtils.getUserFirstCommnetKey();
    if (firstComment && mounted) {
      _textEditingController.text = "";
      showDialog(
          barrierDismissible: false,
          context: context,
          builder: (BuildContext context) {
            return SjMedalObtainDialog(
              assetPath: 'assets/images/xz_bg_3.png',
              content: 'Congratulations on your new medal!',
              onAgree: () {
                SjMedalUtils.instance.updateMedalIsObtain(true, 2);
              },
              onCancel: () {},
            );
          });
    }
  }

  String currentRecordPath = '';
  int duration = 0;

  _recordWidget() {
    if (hiddenRecord) {
      return Container();
    }

    return SjBottomRecorder(
      callback: (path, duration) {
        currentRecordPath = path;
        this.duration = duration;
      },
      sendVoice: () {
        send();
      },
    );
  }

  int selectedIndex = 0;

  _headerWidget() {
    return StatefulBuilder(
      builder: (context, setState) {
        Widget _item(int index, String source) {
          return GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () {
              setState(() {
                selectedIndex = index;
              });
            },
            child: Container(
              margin: const EdgeInsets.only(bottom: 20),
              width: index == selectedIndex ? 50 : 40,
              height: index == selectedIndex ? 50 : 40,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(8),
                border: Border.all(color: index == selectedIndex ? Colors.red : Colors.white),
              ),
              child: Image.asset(source),
            ),
          );
        }

        List<Widget> children = [];
        for (int i = 0; i < works.length; i++) {
          children.add(_item(i, works.elementAt(i)));
        }
        return Stack(
          children: [
            Positioned(
              left: 0,
              right: 0,
              top: 0,
              child: Image.asset(works[selectedIndex], fit: BoxFit.cover, height: 400),
            ),
            Positioned(
              right: 20,
              top: 140,
              child: Column(children: children),
            ),
          ],
        );
      },
    );
  }

  String getMaxStr(String str, int len) {
    return str.length > len ? str.substring(0, len) : str;
  }

  _commentWidget() {
    return Container(
      margin: const EdgeInsets.only(bottom: 30),
      child: ListView.builder(
        padding: EdgeInsets.zero,
        shrinkWrap: true,
        itemCount: comments.length,
        itemBuilder: (context, index) {
          SjWorksCommentModel comment = comments.elementAt(index);
          if (comment.content == null || comment.content!.isEmpty) {
            return Container();
          }
          Widget child = Container();
          if (comment.type == 1) {
            child = Container(
              margin: const EdgeInsets.only(left: 50),
              alignment: Alignment.centerLeft,
              child: Text(
                '${comment.content}',
                style: const TextStyle(fontFamily: 'Galada'),
              ),
            );
          } else {
            child = GestureDetector(
              onTap: () {
                SjRecordUtil.instance.play(comment.content ?? '');
              },
              child: Container(
                alignment: Alignment.centerLeft,
                child: Container(
                  padding: const EdgeInsets.only(left: 10, right: 10, top: 4, bottom: 4),
                  margin: const EdgeInsets.only(left: 40),
                  decoration: BoxDecoration(
                    color: Colors.black,
                    borderRadius: BorderRadius.circular(20),
                  ),
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Image.asset('assets/images/audio_identity.png'),
                      const SizedBox(
                        width: 8,
                      ),
                      Container(
                        alignment: Alignment.center,
                        child: Text(
                          '${comment.duration}S',
                          textAlign: TextAlign.center,
                          style: const TextStyle(fontFamily: 'Galada', color: Colors.white),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            );
          }

          Widget ava = Container();
          if (comment.avatar != null && comment.avatar != '') {
            if (comment.avatar!.startsWith('http')) {
              ava = ClipOval(
                  child: Image.network(
                comment.avatar ?? '',
                fit: BoxFit.cover,
                width: 28.0,
                height: 28.0,
              ));
            } else {
              ava = SizedBox(
                width: 28.0,
                height: 28.0,
                child: ClipOval(
                    child: Image.asset(
                  comment.avatar ?? '',
                  fit: BoxFit.cover,
                )),
              );
            }
          }

          return Container(
            margin: const EdgeInsets.only(left: 20, right: 20),
            child: Column(
              children: [
                Row(
                  children: [
                    ava,
                    const SizedBox(width: 10),
                    Text(
                      '${comment.nickname}',
                      style: const TextStyle(fontFamily: 'Galada'),
                    ),
                  ],
                ),
                child,
              ],
            ),
          );
        },
      ),
    );
  }

  _contentWidget() {
    return Container(
      decoration: const BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/images/post_bg.png'),
          fit: BoxFit.cover,
        ),
      ),
      child: Column(
        children: [
          Container(
              margin: const EdgeInsets.only(top: 20),
              child: Text(getMaxStr(widget.data.title!, 40), style: const TextStyle(fontFamily: 'Galada'))),
          Container(
              alignment: Alignment.centerLeft,
              margin: const EdgeInsets.only(left: 20, right: 20, top: 8),
              child: Text(getMaxStr(widget.data.des!, 40), style: const TextStyle(fontFamily: 'Galada'))),
          if (descTras != '')
            Container(
                alignment: Alignment.centerLeft,
                margin: const EdgeInsets.only(left: 20, right: 20, top: 8),
                child: Text(getMaxStr(descTras, 40), style: const TextStyle(fontFamily: 'Galada'))),
          GestureDetector(
            onTap: () {
              trans();
            },
            child: Container(
              margin: const EdgeInsets.only(right: 20),
              alignment: Alignment.centerRight,
              child: Image.asset('assets/images/transform.png'),
            ),
          ),
          Container(
              height: 8,
              margin: const EdgeInsets.only(top: 20, right: 20, left: 20),
              decoration: BoxDecoration(
                color: const Color(0x33FFFFFF),
                borderRadius: BorderRadius.circular(20),
              )),
          Container(
            margin: const EdgeInsets.only(top: 20, left: 20),
            alignment: Alignment.centerLeft,
            child: Text(
              'Comment(${comments.length})',
              style: const TextStyle(fontFamily: 'Galada', fontSize: 20),
            ),
          ),
          Expanded(
            child: _commentWidget(),
          ),
        ],
      ),
    );
  }

  _bottomWidget() {
    return Container(
      margin: const EdgeInsets.only(bottom: 20, left: 20),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Expanded(
                child: GestureDetector(
                  onTap: () {
                    _focusNode.requestFocus();
                    setState(() {
                      hiddenInput = false;
                    });
                  },
                  child: Container(
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(20),
                      color: Colors.white,
                    ),
                    padding: const EdgeInsets.only(top: 10, bottom: 10, left: 10, right: 10),
                    margin: const EdgeInsets.only(left: 10, bottom: 0, right: 20),
                    child: Row(
                      mainAxisSize: MainAxisSize.max,
                      children: [
                        ClipOval(
                            child: Image.network(
                          widget.data.avatar!,
                          fit: BoxFit.cover,
                          width: 28.0,
                          height: 28.0,
                        )),
                        const SizedBox(width: 4),
                        Container(
                          constraints: const BoxConstraints(maxWidth: 50),
                          child: Text(
                            widget.data.nickname ?? '',
                            style: const TextStyle(fontFamily: 'Galada'),
                            overflow: TextOverflow.clip,
                            maxLines: 1,
                          ),
                        ),
                        const SizedBox(width: 10),
                        Container(
                            padding: const EdgeInsets.only(top: 8, bottom: 8, left: 4, right: 4),
                            decoration: BoxDecoration(
                              color: const Color(0x0D000000),
                              borderRadius: BorderRadius.circular(12),
                            ),
                            child: const Text('Say Something...', style: TextStyle(fontFamily: 'Galada', color: Color(0x26000000)))),
                      ],
                    ),
                  ),
                ),
              ),
              BlocBuilder<SjHomeBloc, SjHomeState>(
                buildWhen: (previous, current) {
                  return previous.worksList != current.worksList;
                },
                builder: (context, state) {
                  return IconButton(
                    onPressed: () {
                      if (isLiked == true) {
                        doUnlike();
                        isLiked = false;
                      } else {
                        doLike();
                        isLiked = true;
                      }
                      setState(() {});
                    },
                    icon: Image.asset(isLiked == true ? 'assets/images/like.png' : 'assets/images/un_like.png'),
                    iconSize: 60,
                  );
                },
              ),
              const SizedBox(width: 20),
            ],
          ),
        ],
      ),
    );
  }
}
